const axios = require('axios');

const API_BASE = 'http://localhost:3000';

async function testSessionCreation() {
  console.log('开始测试会话创建功能...\n');
  
  try {
    // 测试1: 正常创建会话
    console.log('1. 测试正常创建会话');
    const createRes = await axios.post(`${API_BASE}/chats/openOrCreate`, {
      fromUserId: '68aeed055e85b6f7f7ff0480',
      targetType: 'hospital',
      targetId: 'hospital_001',
      targetName: '北京医美医院'
    });
    
    console.log('✅ 创建会话成功:', createRes.data);
    const chatId = createRes.data._id;
    
    // 测试2: 重复创建相同会话（应该返回现有会话）
    console.log('\n2. 测试重复创建相同会话');
    const duplicateRes = await axios.post(`${API_BASE}/chats/openOrCreate`, {
      fromUserId: '68aeed055e85b6f7f7ff0480',
      targetType: 'hospital',
      targetId: 'hospital_001',
      targetName: '北京医美医院'
    });
    
    console.log('✅ 重复创建结果:', duplicateRes.data);
    console.log('会话ID是否相同:', chatId === duplicateRes.data._id);
    
    // 测试3: 创建医生会话
    console.log('\n3. 测试创建医生会话');
    const doctorRes = await axios.post(`${API_BASE}/chats/openOrCreate`, {
      fromUserId: '68aeed055e85b6f7f7ff0480',
      targetType: 'doctor',
      targetId: 'doctor_001',
      targetName: '张医生'
    });
    
    console.log('✅ 创建医生会话成功:', doctorRes.data);
    
    // 测试4: 参数缺失测试
    console.log('\n4. 测试参数缺失情况');
    try {
      await axios.post(`${API_BASE}/chats/openOrCreate`, {
        fromUserId: '68aeed055e85b6f7f7ff0480',
        // 缺少 targetType 和 targetId
      });
    } catch (error) {
      console.log('✅ 参数缺失测试通过:', error.response?.data?.error);
    }
    
    console.log('\n🎉 所有测试完成！');
    
  } catch (error) {
    console.error('❌ 测试失败:', error.response?.data || error.message);
    
    if (error.code === 'ECONNREFUSED') {
      console.log('\n💡 提示: 请确保后端服务已启动 (npm start)');
    }
  }
}

// 运行测试
testSessionCreation();
